package com.honghu.cloud.tools;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.swing.ImageIcon;

import com.google.common.collect.Lists;
import com.honghu.cloud.utils.Exceptions;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统工具类，用来快速处理,系统默认将该工具类添加到ModelAndView中，前台可以使用$!CommUtil.xxx调用该工具类
 * @author Administrator
 *
 */
@Slf4j
public class CommUtil {
	
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	public static String getURL(HttpServletRequest request) {
		String contextPath = request.getContextPath().equals("/") ? ""
				: request.getContextPath();
		String url = "http://" + request.getServerName();
		if (null2Int(Integer.valueOf(request.getServerPort())) != 80) {
			url = url + ":"
					+ null2Int(Integer.valueOf(request.getServerPort()))
					+ contextPath;
		} else {
			url = url + contextPath;
		}
		return url;
	}
	
	public static int null2Int(Object s) {
		int v = 0;
		if (s != null) {
			try {
				v = Integer.parseInt(s.toString());
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	public static String null2String(Object s) {
		return s == null ? "" : s.toString().trim();
	}
	
	public static Long null2Long(Object s) {
		Long v = Long.valueOf(-1L);
		if (s != null) {
			try {
				v = Long.valueOf(Long.parseLong(s.toString()));
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	public static double null2Double(Object s) {
		double v = 0.0D;
		if (s != null) {
			try {
				v = Double.parseDouble(null2String(s));
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	
	/**
	 * 计算当前域名，不含www的顶级域名
	 * 
	 * @param request
	 * @return
	 */
	public static String generic_domain(HttpServletRequest request) {
		String system_domain = "localhost";
		String serverName = request.getServerName();
		if (isIp(serverName)) {
			system_domain = serverName;
		} else if (serverName.indexOf(".") == serverName.lastIndexOf(".")) {
			system_domain = serverName;
		} else {
			system_domain = serverName.substring(serverName.indexOf(".") + 1);
		}
		return system_domain;
	}
	
	/**
	 * 判断是否是一个IP
	 * 
	 * @param IP
	 * @return
	 */
	public static boolean isIp(String IP) {
		boolean b = false;
		IP = trimSpaces(IP);
		if (IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
			String[] s = IP.split("\\.");
			if ((Integer.parseInt(s[0]) < 255)
					&& (Integer.parseInt(s[1]) < 255)
					&& (Integer.parseInt(s[2]) < 255)
					&& (Integer.parseInt(s[3]) < 255)) {
				b = true;
			}
		}
		return b;
	}
	
	/**
	 * 去掉IP字符串前后所有的空格
	 * 
	 * @param IP
	 * @return
	 */
	public static String trimSpaces(String IP) {
		while (IP.startsWith(" ")) {
			IP = IP.substring(1, IP.length()).trim();
		}
		while (IP.endsWith(" ")) {
			IP = IP.substring(0, IP.length() - 1).trim();
		}
		return IP;
	}
	
	/**
	 * 读取图片为bufferedimage,修正图片读取ICC信息丢失而导致出现红色遮罩
	 * 
	 * @param image
	 * @return
	 */
	public static BufferedImage toBufferedImage(Image image) {
		if ((image instanceof BufferedImage)) {
			return (BufferedImage) image;
		}
		image = new ImageIcon(image).getImage();

		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		try {
			int transparency = 1;

			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(image.getWidth(null),
					image.getHeight(null), transparency);
		} catch (HeadlessException localHeadlessException) {
		}
		if (bimage == null) {
			int type = 1;

			bimage = new BufferedImage(image.getWidth(null),
					image.getHeight(null), type);
		}
		Graphics g = bimage.createGraphics();

		g.drawImage(image, 0, 0, null);
		g.dispose();

		return bimage;
	}
	
	public static String formatShortDate(Object v) {
		if (v == null) {
			return null;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(v);
	}

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		if (ip.equals("0:0:0:0:0:0:0:1")) {
			InetAddress addr = null;
			try {
				addr = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				log.error(Exceptions.getStackTraceAsString(e));
			}
			ip = null2String(addr.getHostAddress());
		}
		if ((ip != null) && (!ip.equalsIgnoreCase("unknown")) && (!isIp(ip))) {
			String[] ips = ip.split(",");
			if (ips.length > 0) {
				ip = ips[0];
			}
		}
		return ip;
	}
	
	
	/**
	 * 浮点数乘法
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static double mul(Object a, Object b) {
		BigDecimal e = new BigDecimal(null2Double(a));
		BigDecimal f = new BigDecimal(null2Double(b));
		double ret = e.multiply(f).doubleValue();
		DecimalFormat df = new DecimalFormat("0.00");
		return Double.valueOf(df.format(ret)).doubleValue();
	}
	
	public static String formatMoney(Object money) {
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(money);
	}
	
	
	/**
	 * 浮点数据加法
	 * @param a
	 * @param b
	 * @return
	 */
	public static double add(Object a, Object b) {
		double ret = 0.0D;
		BigDecimal e = new BigDecimal(null2Double(a));
		BigDecimal f = new BigDecimal(null2Double(b));
		ret = e.add(f).doubleValue();
		DecimalFormat df = new DecimalFormat("0.00");
		return Double.valueOf(df.format(ret)).doubleValue();
	}
	
	public static String formatLongDate(Object v) {
		if ((v == null) || (v.equals(""))) {
			return "";
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(v);
	}
	
	public static Date formatDate(String s) {
		Date d = null;
		try {
			d = dateFormat.parse(s);
		} catch (Exception localException) {
		}
		return d;
	}
	
	public static Date formatDate(String s, String format) {
		Date d = null;
		try {
			SimpleDateFormat dFormat = new SimpleDateFormat(format);
			d = dFormat.parse(s);
		} catch (Exception localException) {
		}
		return d;
	}
	
	public static boolean null2Boolean(Object s) {
		boolean v = false;
		if (s != null) {
			try {
				v = Boolean.parseBoolean(s.toString());
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	public static float null2Float(Object s) {
		float v = 0.0F;
		if (s != null) {
			try {
				v = Float.parseFloat(s.toString());
			} catch (Exception localException) {
			}
		}
		return v;
	}
	
	/**
	 * 浮点数除法运算，保证数据的精确度
	 * @param a
	 * @param b
	 * @return
	 */
	public static double div(Object a, Object b) {
		double ret = 0.0D;
		if ((!null2String(a).equals("")) && (!null2String(b).equals(""))) {
			BigDecimal e = new BigDecimal(null2String(a));
			BigDecimal f = new BigDecimal(null2String(b));
			if (null2Double(f) > 0.0D) {
				ret = e.divide(f, 3, 1).doubleValue();
			}
		}
		DecimalFormat df = new DecimalFormat("0.00");
		return Double.valueOf(df.format(ret)).doubleValue();
	}
	
	
	/**
	 * ajax动态分页，使用json管理数据
	 * @param url
	 * @param params
	 * @param currentPage
	 * @param pages
	 * @return
	 */
	public static String showPageAjaxHtml(String url, String params,
			int currentPage, int pages, int pageSize) {
		if (url != null && url.contains(".html")) {
			url = url.replace(".html", "");
		}
		String s = "";
		if (pages > 0) {
			String address = url + "?1=1" + params;
			if (currentPage >= 1) {
				s = s + "<a href='javascript:void(0);' onclick='return ajaxPage(\""
						+ address + "\",1,this)'>首页</a> ";
				s = s + "<a href='javascript:void(0);' onclick='return ajaxPage(\""
						+ address + "\"," + (currentPage - 1)
						+ ",this)'><b><</b>上一页</a> ";
			}
			int beginPage = currentPage - 3 < 1 ? 1 : currentPage - 3;
			if (beginPage <= pages) {
				s = s + "第　";
				int i = beginPage;
				for (int j = 0; (i <= pages) && (j < 6); j++) {
					if (i == currentPage) {
						s = s + "<a class='this' href='javascript:void(0);' onclick='return ajaxPage(\""
									+ address + "\"," + i + ",this)'>" + i
								+ "</a> ";
					} else {
						s = s + "<a href='javascript:void(0);' onclick='return ajaxPage(\""
									+ address + "\"," + i + ",this)'>" + i
								+ "</a> ";
					}
					i++;
				}
				s = s + "页　";
			}
			if (currentPage <= pages) {
				s = s + "<a href='javascript:void(0);' onclick='return ajaxPage(\""
						+ address + "\"," + (currentPage + 1)
						+ ",this)'>下一页<b class='next'>></b></a> ";
				s = s + "<a href='javascript:void(0);' onclick='return ajaxPage(\""
						+ address + "\"," + pages + ",this)'>末页</a> ";
			}
			s = s + "共<strong>" + pages + "</strong>页 ";
			s = s + " 转到<input type='text' class='ip_txt' value=''/>页  <a onclick='return goto_ajaxPage(\""
					+ address + "\",\"\",this)' href='javascript:void(0);'>确定</a>";
		}
		return s;
	}
	
	
	/**
	 * 浮点数据减法运算，保证数据的精确度
	 * @param a
	 * @param b
	 * @return
	 */
	public static double subtract(Object a, Object b) {
		double ret = 0.0D;
		BigDecimal e = new BigDecimal(null2Double(a));
		BigDecimal f = new BigDecimal(null2Double(b));
		ret = e.subtract(f).doubleValue();
		DecimalFormat df = new DecimalFormat("0.00");
		return Double.valueOf(df.format(ret)).doubleValue();
	}
	
	public static final String randomInt(int length) {
		if (length < 1) {
			return null;
		}
		Random randGen = new Random();
		char[] numbersAndLetters = "0123456789".toCharArray();

		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(10)];
		}
		return new String(randBuffer);
	}
	
	public static final String randomString(int length) {
		char[] numbersAndLetters = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
				.toCharArray();
		if (length < 1) {
			return "";
		}
		Random randGen = new Random();
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}
	
	public static String formatTime(String format, Object v) {
		if (v == null) {
			return null;
		}
		if (v.equals("")) {
			return "";
		}
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(v);
	}

	public static String formatTime(String date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(date);
		return df.format(date);
	}
	
	public static String first2upper(String str) {
		String s = "";
		s = str.substring(0, 1).toUpperCase() + str.substring(1);
		return s;
	}
	
	
	/**
	 * 替换图片,上下文
	 * @param imgWebServer 文件地址前缀 http://localhost:9001/
	 * @param content
	 * @return
	 */
	public static String addImgWebServer2(String imgWebServer, String content) {
		if (content == null) {
			return "";
		}
		String[] urls = content.split("<img");
		String s = "";
		
		for (String u : urls) {
			if(!u.contains("src")){
				s += u;
				continue;
			}
			
			if(u.contains("<embed")) {
				s += u;
				continue;
			}
			
			if (!u.contains("/upload") && u.contains("/store")
					&& u.contains("http")) {
				String oldImageServer = u.substring(u.indexOf("http://"),
						u.indexOf("/store"));
				u = u.replaceAll(oldImageServer, imgWebServer);
			}
			
			if (u.contains("/upload") && u.contains("http") ) {
				if(u.contains("iframe")){
					String oldImageServer = u.substring(u.indexOf("http://"),
							u.indexOf("/resources"));
					u = u.replaceAll(oldImageServer, imgWebServer);
				}else {
					String oldImageServer = u.substring(u.indexOf("http://"),
							u.indexOf("/upload"));
					u = u.replaceAll(oldImageServer, imgWebServer);
					
				}
				
			}
			
			
			
			if (u.contains("/upload") && !u.contains("http")) {
				u = u.replaceAll("/upload", imgWebServer+"/upload");
			}
			
			if (u.trim().length() > 0) {
				s += "<img" + u;
			} else {
				s += u;
			}
		}

		return s;
	}
	
	public static boolean createFolder(String folderPath) {
		boolean ret = true;
		try {
			File myFilePath = new File(folderPath);
			if ((!myFilePath.exists()) && (!myFilePath.isDirectory())) {
				ret = myFilePath.mkdirs();
			}
		} catch (Exception e) {
			ret = false;
		}
		return ret;
	}
	
	/**
	 * 前台判定是否存在文件
	 * 
	 * @param path
	 * @return
	 */
	public static boolean fileExist(String path) {
		File file = new File(path);
		return file.exists();
	}

	public static boolean createSmall(String target, InputStream input, Integer smallWidth, Integer smallHeight) {

		BufferedImage bis = null;
		Image img = null;
		try {
			
			try {
				img = Toolkit.getDefaultToolkit().createImage(toByteArray(input));
				bis = toBufferedImage(img);
			} catch (Exception e) {
				log.error("");
			}
			int w = bis.getWidth();
			int h = bis.getHeight();
			if (w == 0) {
				w = 160;
			}

			if (h == 0) {
				h = 160;
			}
			
			try {
				ImageCompress.ImageScale(img, target, smallWidth, smallHeight);
			} catch (Exception e) {
				log.error(Exceptions.getStackTraceAsString(e));
				return false;
			}
			return true;
		} catch (Exception e) {
			
		}finally{
			if(bis != null){
				bis.flush();
			}
			if(img != null){
				img.flush();
			}
			
		}
		return false;
	
		
	}
	
	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024*4];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}

	public static boolean isImg(String extend) {
		boolean ret = false;
		List<String> list = Lists.newArrayList();
		list.add("jpg");
		list.add("jpeg");
		list.add("bmp");
		list.add("gif");
		list.add("png");
		list.add("mp4");
		list.add("tif");
		list.add("tbi");
		for (String s : list) {
			if (s.equals(extend)) {
				ret = true;
			}
		}
		return ret;
	}

}
